package param

import (
	"log"
	"strings"
	"path"
	"io/ioutil"
	"encoding/json"
	"os/exec"
	"os"
	"path/filepath"
)

type SysParam struct {
	Users []UserParam
}

var param *SysParam

var userAgentParam *UserAgentParam

func LoadParam() error {
	var err error
	currentPath, err := GetCurrentPath()
	if err != nil {
		log.Fatal("获取当前目录失败")
		return err
	}
	//fmt.Println(currentPath)
	configPath := strings.Replace(path.Join(currentPath, "config", "config.json"), "\\", "/", -1)
	//fmt.Println(path)
	param, err = parseParamFile(configPath)
	if err != nil {
		return err
	}
	userAgentPath := strings.Replace(path.Join(currentPath, "config", "UserAgent.json"), "\\", "/", -1)
	userAgentParam, err = parseUserAgentFile(userAgentPath)
	if err != nil {
		return err
	}
	userAgentParam.init()
	return nil
}

func GetParam() *SysParam {
	return param
}
func GetUserAgentParam() *UserAgentParam {
	return userAgentParam
}

//创建文件初始化参数处理器
func parseParamFile(filename string) (*SysParam, error) {
	if filename == "" {
		log.Fatal("系统参数路径为空")
		return nil, nil
	}
	file, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatal("读取配置文件失败")
		return nil, err
	}
	param := &SysParam{}
	err = json.Unmarshal(file, &param)
	if err != nil {
		log.Fatal("解析配置文件失败")
		return nil, err
	}
	return param,nil
}
//创建文件初始化参数处理器
func parseUserAgentFile(filename string) (*UserAgentParam, error) {
	if filename == "" {
		log.Fatal("系统参数路径为空")
		return nil, nil
	}
	file, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatal("读取useragent配置文件失败")
		return nil, err
	}
	param := &UserAgentParam{}
	err = json.Unmarshal(file, &param)
	if err != nil {
		log.Fatal("解析useragent配置文件失败")
		return nil, err
	}
	return param,nil
}

func GetCurrentPath() (string,error)  {
	file,err:=exec.LookPath(os.Args[0])
	if err != nil{
		return "",err
	}
	path,err:=filepath.Abs(file)
	if err != nil {
		return "",err
	}
	path=strings.Replace(path,"\\","/",-1)
	i:=strings.LastIndex(path,"/")
	result:=string(path[0:i+1])
	return result,nil
}
